package com.yuntianshi.controller;

import com.alibaba.fastjson.JSON;
import com.yuntianshi.common.*;
import com.yuntianshi.pojo.Member;
import com.yuntianshi.service.MemberService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * 会员登录
 */
@RestController
@RequestMapping("/member")
public class MemberController {

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @Autowired
    private MemberService memberService;
//    @Autowired
//    private JedisPool jedisPool;

    //使用手机号和验证码登录
    @RequestMapping("/login")
    public Result login(HttpServletResponse response, @RequestBody Map map){
        String telephone = (String) map.get("telephone");
        String validateCode = (String) map.get("validateCode");
        //从Redis中获取缓存的验证码
        String codeInRedis = redisTemplate.opsForValue().get(telephone + RedisMessageConstant.SENDTYPE_LOGIN);
        System.out.println(codeInRedis);
        //String codeInRedis =
                //jedisPool.getResource().get(telephone+ RedisMessageConstant.SENDTYPE_LOGIN);
        if(codeInRedis == null || !codeInRedis.equals(validateCode)){
            //验证码输入错误
            return new Result(false, MessageContant.VALIDATECODE_ERROR);
        }else{
            //验证码输入正确
            //判断当前用户是否为会员
            Member member = memberService.findByTelephone(telephone);
            if(member == null){
                //当前用户不是会员，自动完成注册
                member = new Member();
                member.setPhoneNumber(telephone);
                member.setRegTime(new Date());
                memberService.add(member);
            }
            //登录成功
            //写入Cookie，跟踪用户
            Cookie cookie = new Cookie("login_member_telephone",telephone);
            cookie.setPath("/");//路径
            cookie.setMaxAge(60*60*24*30);//有效期30天
            response.addCookie(cookie);
            //保存会员信息到Redis中
            String json = JSON.toJSON(member).toString();
            //jedisPool.getResource().setex(telephone,60*30,json);
            redisTemplate.opsForValue().set(telephone,json,30, TimeUnit.DAYS);
            return new Result(true,MessageContant.LOGIN_SUCCESS);
        }
    }

    //分页查询
    @RequestMapping("/findPage")
    public PageResult findPage(@RequestBody QueryPageBean queryPageBean){
        PageResult pageResult = memberService.pageQuery(
                queryPageBean.getCurrentPage(),
                queryPageBean.getPageSize(),
                queryPageBean.getQueryString());
        return pageResult;
    }

    @RequestMapping("/add")
    public Result add(@RequestBody Member member){
        try {
            //判断该手机号会员是否注册
            Member memberByTelephone = memberService.findByTelephone(member.getPhoneNumber());
            if (memberByTelephone!=null){
                return new Result(false,"添加会员失败，改手机号已注册");
            }
            memberService.add(member);
        }catch (Exception e){
            e.printStackTrace();
            return new Result(false,MessageContant.ADD_MEMBER_FAIL);
        }
        return new Result(true,MessageContant.ADD_MEMBER_SUCCESS);
    }

    @RequestMapping("/delete")
    public Result delete(Integer id){
        try {
            memberService.delete(id);
        }catch (Exception e){
            e.printStackTrace();
            return new Result(false,MessageContant.DELETE_MEMBER_FAIL);
        }
        return new Result(true,MessageContant.DELETE_MEMBER_SUCCESS);
    }

    @RequestMapping("/findById")
    public Result findById(Integer id){
        try {
            Member member = memberService.findById(id);
            return new Result(true,MessageContant.QUERY_MEMBER_SUCCESS,member);
        }catch (Exception e){
            e.printStackTrace();
            return new Result(false,MessageContant.QUERY_MEMBER_FAIL);
        }
    }

    @RequestMapping("/edit")
    public Result edit(@RequestBody Member member){
        try {
            memberService.edit(member);
        }catch (RuntimeException e){
            e.printStackTrace();
            return new Result(false,e.getMessage());
        }catch (Exception e){
            return new Result(false,MessageContant.EDIT_MEMBER_FAIL);
        }
        return new Result(true,MessageContant.EDIT_MEMBER_SUCCESS);
    }

    @RequestMapping("/findByTelephone")
    public Result findByTelephone(@CookieValue("login_member_telephone") String telephone){
        try {
            Member member = memberService.findByTelephone(telephone);
            return new Result(true,MessageContant.QUERY_MEMBER_SUCCESS,member);
        }catch (Exception e){
            e.printStackTrace();
            return new Result(false,MessageContant.QUERY_MEMBER_FAIL);
        }
    }

    @RequestMapping("/memberEdit")
    public Result memberEdit(HttpServletResponse response,
                             @RequestBody Map map,
                             @CookieValue("login_member_telephone") String telephone){
        //判断验证码受否正确
        String phoneNumber = (String) map.get("phoneNumber");
        //从Redis中获取缓存的验证码，key为手机号+RedisConstant.SENDTYPE_ORDER
        String codeInRedis = redisTemplate.opsForValue().get(phoneNumber + RedisMessageConstant.SENDTYPE_ORDER);
        String validateCode = (String) map.get("validateCode");
        //校验手机验证码
        if(codeInRedis == null || !codeInRedis.equals(validateCode)){
            return new Result(false, MessageContant.VALIDATECODE_ERROR);
        }
        try {
            //判断用户是否更改手机号
            if (telephone.equals(phoneNumber)){
                //未更换手机号
                Member member = new Member();
                member.setId((Integer) map.get("id"));
                member.setName((String) map.get("name"));
                member.setSex((String) map.get("sex"));
                member.setIdCard((String) map.get("idCard"));
                member.setEmail((String) map.get("email"));
//            member.setPhoneNumber((String) map.get("phoneNumber"));
                memberService.edit(member);
                return new Result(true,"信息修改成功");
            }else {
                //更换手机号
                Member member = new Member();
                member.setId(((Double) map.get("id")).intValue());
                member.setName((String) map.get("name"));
                member.setSex((String) map.get("sex"));
                member.setIdCard((String) map.get("idCard"));
                member.setEmail((String) map.get("email"));
                member.setPhoneNumber((String) map.get("phoneNumber"));
                member.setFileNumber((String) map.get("phoneNumber"));
                memberService.edit(member);
                //重新写入Cookie，跟踪用户
                Cookie cookie = new Cookie("login_member_telephone",phoneNumber);
                cookie.setPath("/");//路径
                cookie.setMaxAge(60*60*24*30);//有效期30天
                response.addCookie(cookie);
                //保存会员信息到Redis中
                String json = JSON.toJSON(member).toString();
                redisTemplate.opsForValue().set(phoneNumber,json,30, TimeUnit.DAYS);
                return new Result(true,"信息修改成功");
            }
        }catch (Exception e){
            e.printStackTrace();
            return new Result(false,"信息修改失败，请重试");
        }
    }

}
